import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import { HttpService } from './http.service';

@Injectable({
  providedIn: 'root'
})
export class MineService {

  private loginStatus: boolean = null;

  private loginUser: any = null;

  private accessToken: string = null;

  private refreshToken: string = null;

  private mineSubject = new Subject<any>();

  constructor(private httpService: HttpService) { }

  getAccessToken(): string {
    return this.accessToken;
  }

  getRefreshToken(): string {
    return this.refreshToken;
  }

  async checkUserLogin() {
    if (this.loginStatus != null) {
      return this.loginStatus
    }

    this.loginStatus = false

    if (!this.refreshToken) {
      this.refreshToken = localStorage.getItem('refreshToken');
    }

    if (this.refreshToken) {
      const tokenResult = await this.httpService.renewalToken(this.refreshToken)
      if (tokenResult.code == 0) {
        this.accessToken = tokenResult.data
        const userResult = await this.httpService.getLoginUserInfo()
        this.loginUser = userResult.data
        this.mineSubject.next(userResult.data)
        this.loginStatus = true
      }
    }
    return this.loginStatus
  }

  public getLoginDataObservable() {
    return this.mineSubject.asObservable();
  }

  public setLoginData(data) {
    localStorage.setItem('refreshToken', data.refreshToken)
    this.accessToken = data.accessToken
    this.refreshToken = data.refreshToken
    this.loginUser = data.user
    this.loginStatus = true
    this.mineSubject.next(data.user)
  }

  public getPhotoUrl() {
    return this.loginUser.photoUrl
  }

  public setPhotoUrl(url) {
    this.loginUser.photoUrl = url
    this.mineSubject.next(this.loginUser)
  }

  public resetLoginData() {
    localStorage.removeItem('refreshToken')
    this.accessToken = null
    this.refreshToken = null
    this.loginUser = null
    this.loginStatus = false
  }
}
